<template>
  <div class="cashback-management">
    <div class="page-header">
      <h2>返现管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="返现名称">
          <el-input v-model="searchForm.cashbackName" placeholder="请输入返现名称" clearable />
        </el-form-item>
        <el-form-item label="返现规则">
          <el-select v-model="searchForm.cashbackType" placeholder="请选择返现规则" clearable>
            <el-option label="随机返现" :value="1" />
            <el-option label="限额返现" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="返现范围">
          <el-select v-model="searchForm.cashbackScope" placeholder="请选择返现范围" clearable>
            <el-option label="全部商品" :value="1" />
            <el-option label="电子用品" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="返现状态">
          <el-select v-model="searchForm.cashbackState" placeholder="请选择状态" clearable>
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchCashback">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增返现
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="cashbackList" v-loading="loading" stripe>
        <el-table-column prop="cashbackId" label="返现ID" width="80" />
        <el-table-column prop="cashbackName" label="返现名称" width="200" />
        <el-table-column prop="cashbackType" label="返现规则" width="120">
          <template #default="{ row }">
            <el-tag :type="row.cashbackType === 1 ? 'success' : 'warning'">
              {{ getCashbackTypeText(row.cashbackType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cashbackRange" label="返现范围" width="200" />
        <el-table-column prop="cashbackScope" label="返现范围类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.cashbackScope === 1 ? 'primary' : 'info'">
              {{ getCashbackScopeText(row.cashbackScope) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cashbackState" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStateType(row.cashbackState)">
              {{ getStateText(row.cashbackState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editCashback(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteCashback(row.cashbackId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑返现' : '新增返现'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="cashbackForm" :rules="cashbackRules" ref="cashbackFormRef" label-width="120px">
        <el-form-item label="返现名称" prop="cashbackName">
          <el-input v-model="cashbackForm.cashbackName" placeholder="请输入返现名称" />
        </el-form-item>
        <el-form-item label="返现规则" prop="cashbackType">
          <el-select v-model="cashbackForm.cashbackType" placeholder="请选择返现规则">
            <el-option label="随机返现" :value="1" />
            <el-option label="限额返现" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="返现范围" prop="cashbackRange">
          <el-input v-model="cashbackForm.cashbackRange" placeholder="请输入返现范围" />
        </el-form-item>
        <el-form-item label="返现范围类型" prop="cashbackScope">
          <el-select v-model="cashbackForm.cashbackScope" placeholder="请选择返现范围类型">
            <el-option label="全部商品" :value="1" />
            <el-option label="电子用品" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="返现状态" prop="cashbackState">
          <el-select v-model="cashbackForm.cashbackState" placeholder="请选择状态">
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="cashbackForm.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="cashbackForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { cashbackApi } from '@/api/cashback'

// 响应式数据
const loading = ref(false)
const cashbackList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const cashbackFormRef = ref()

// 搜索表单
const searchForm = reactive({
  cashbackName: '',
  cashbackType: null,
  cashbackScope: null,
  cashbackState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 返现表单
const cashbackForm = reactive({
  cashbackId: null,
  cashbackName: '',
  cashbackType: null,
  cashbackRange: '',
  cashbackScope: null,
  cashbackState: null,
  startTime: '',
  endTime: ''
})

// 表单验证规则
const cashbackRules = {
  cashbackName: [
    { required: true, message: '请输入返现名称', trigger: 'blur' }
  ],
  cashbackType: [
    { required: true, message: '请选择返现类型', trigger: 'change' }
  ],
  cashbackRange: [
    { required: true, message: '请输入返现范围', trigger: 'blur' }
  ],
  cashbackScope: [
    { required: true, message: '请选择返现范围类型', trigger: 'change' }
  ],
  cashbackState: [
    { required: true, message: '请选择返现状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 获取返现规则文本
const getCashbackTypeText = (type) => {
  const typeMap = {
    1: '随机返现',
    2: '限额返现'
  }
  return typeMap[type] || '未知'
}

// 获取返现范围类型文本
const getCashbackScopeText = (scope) => {
  const scopeMap = {
    1: '全部商品',
    2: '电子用品'
  }
  return scopeMap[scope] || '未知'
}

// 获取状态类型
const getStateType = (state) => {
  const stateMap = {
    1: 'success',
    2: 'danger'
  }
  return stateMap[state] || 'info'
}

// 获取状态文本
const getStateText = (state) => {
  const stateMap = {
    1: '进行中',
    2: '已终止'
  }
  return stateMap[state] || '未知'
}

// 搜索返现
const searchCashback = async () => {
  loading.value = true
  try {
    const response = await cashbackApi.getCashbackList(searchForm)
    if (response.code === 200) {
      cashbackList.value = response.data || []
      pagination.total = cashbackList.value.length
    }
  } catch (error) {
    console.error('搜索返现失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    cashbackName: '',
    cashbackType: null,
    cashbackScope: null,
    cashbackState: null
  })
  searchCashback()
}

// 编辑返现
const editCashback = (row) => {
  isEdit.value = true
  Object.assign(cashbackForm, row)
  showAddDialog.value = true
}

// 删除返现
const deleteCashback = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个返现活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await cashbackApi.deleteCashback(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchCashback()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除返现失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await cashbackFormRef.value.validate()

    const response = isEdit.value
      ? await cashbackApi.updateCashback(cashbackForm)
      : await cashbackApi.addCashback(cashbackForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchCashback()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(cashbackForm, {
    cashbackId: null,
    cashbackName: '',
    cashbackType: null,
    cashbackRange: '',
    cashbackScope: null,
    cashbackState: null,
    startTime: '',
    endTime: ''
  })
  isEdit.value = false
  cashbackFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchCashback()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchCashback()
}

// 初始化
onMounted(() => {
  searchCashback()
})
</script>

<style scoped>
.cashback-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>